package com.hengxinguotong.hxgtwygsp.utils;

import com.hengxinguotong.hxgtwygsp.ui.main.picture.PictureFragment;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;

/**
 * TODO
 *
 * @author hjz
 * @version V1.0.0
 * @since 2019/3/29 18:21
 */

public class TimeDown
{
    private Disposable disposable;
    private int remainTime;
    private LifecycleTransformer<Long> transformer;
    private Callback callback;
    private int customTime = 10;

    public TimeDown(LifecycleTransformer<Long> transformer, Callback callback)
    {
        this.transformer = transformer;
        this.callback = callback;
    }

    public TimeDown(LifecycleTransformer<Long> transformer, Callback callback, int customTime)
    {
        this.transformer = transformer;
        this.callback = callback;
        this.customTime = customTime;
    }

    public void startTimer()
    {
        disposable = Observable.interval(1, 1, TimeUnit.SECONDS, Schedulers.io())
                .doOnSubscribe(disposable -> recoverRemainTime())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(transformer)
                .subscribe(aLong ->
                {
                    remainTime--;
                    if (remainTime == 0)
                    {
                        if (callback != null)
                        {
                            callback.onComplete();
                        }
                        disposable.dispose();
                    }
                });
    }

    public void stop()
    {
        if (disposable != null && !disposable.isDisposed())
        {
            disposable.dispose();
        }
    }

    public void recoverRemainTime()
    {
        remainTime = customTime;
    }

    public interface Callback
    {
        void onComplete();
    }
}
